package com.juyu.miliao.authentication.security;

import com.juyu.miliao.common.domain.CommonHead;
import com.juyu.miliao.common.exception.IllegalParamException;
import com.juyu.miliao.common.security.exception.IllegalPasswordFormatException;
import com.juyu.miliao.common.security.exception.IllegalUsernameFormatFormatException;
import com.juyu.miliao.common.util.IpUtil;
import com.juyu.miliao.common.util.VerifyUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;

/**
 *  手机验证码登录过滤器
 * @Auther: 卜加超
 * @Date: 2019/4/26 09:12
 * @Description:
 */
public class VerifyUsernameVerificationCodeAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    public VerifyUsernameVerificationCodeAuthenticationFilter(String filterProcessesUrl) {
        super(new AntPathRequestMatcher(filterProcessesUrl, "POST"));
    }

    public VerifyUsernameVerificationCodeAuthenticationFilter() {
        super(new AntPathRequestMatcher("/login/username", "POST"));
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse httpServletResponse) throws AuthenticationException, IOException, ServletException {
        //验证手机号
        String username = request.getParameter("username");
        if (username == null)
            throw new IllegalUsernameFormatFormatException();
        username = username.trim();
        if (!username.matches("^[0-9A-Za-z]{5,16}$"))
            throw new IllegalUsernameFormatFormatException("username:" + username);
        //验证验证码
        String verificationCode = request.getParameter("verificationCode");

        if(verificationCode == null || verificationCode.equals(""))
            throw new IllegalParamException("verificationCode:","验证码不能为空");
        verificationCode = verificationCode.trim();

        String ip = IpUtil.getIPv4Address(request);
        CommonHead com = VerifyUtil.verifyCommonHead(request);

        UserNameVerificationCodeToken authRequest = new UserNameVerificationCodeToken(username,ip,verificationCode,com);
        return this.getAuthenticationManager().authenticate(authRequest);
    }
}
